﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Hybrid.Threading.Sync
{
    class Program
    {
        static void Main(string[] args)
        {
            SomeMethod();
            //LazyInitializerDemo();
        }

        static void LazyDemo()
        {
            //创建一个延迟初始化包装器,用它将DateTime的获取包装起来
            Lazy<string> s = new Lazy<string>(() => DateTime.Now.ToString(), LazyThreadSafetyMode.PublicationOnly);
            
            Console.WriteLine(s.IsValueCreated);//还没有查询Value,返回false
            Console.WriteLine(s.Value);//现在调用委托
            Console.WriteLine(s.IsValueCreated);//已经查询Value,返回true
            Thread.Sleep(10000);//等待10秒,再次显示
            Console.WriteLine(s.Value);//委托没有调用,显示相同结果
        }

        static void LazyInitializerDemo()
        {
            string name = string.Empty;
            bool is_create = false;
            object obj_lock = null;
            LazyInitializer.EnsureInitialized(ref name, ref is_create, ref obj_lock, () => "Jeffrey");
            Console.WriteLine(name);
            LazyInitializer.EnsureInitialized(ref name, ref is_create, ref obj_lock, () => "Richter");
            Console.WriteLine(name);
        }

        public static void SomeMethod()
        {
            var t = new Transaction();
            Monitor.Enter(t); // 这个线程获取对象的公共锁
            // 让一个线程池线程显示LastTransaction时间
            // 注意:线程池线程会阻塞,直到SomeMethod调用了Monitor.Exit
            ThreadPool.QueueUserWorkItem(o => Console.WriteLine(t.LastTransaction));
            Monitor.Exit(t);
        }


    }
}
